package Server.ExtComponents.socket;


import Server.ExtComponents.BaseConfig.MServerConfig;
import Server.ServerCore.Service.Logic.ProcessSession;
import Server.ServerCore.Model.Player.PlayerInstance;
import Server.ServerCore.Service.service.PlayerManagerService;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.execution.ExecutionHandler;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

public final class MServerFrameHandler extends SimpleChannelUpstreamHandler {
    private static final Logger LOG = LoggerFactory.getLogger(MServerFrameHandler.class);
    private ObjectSession objectSession=null;
    private ProcessSession processSession=null;
    private PlayerInstance player=null;

    /**记录服务器在线人数*/
    public static final AtomicInteger countConnection=new AtomicInteger(0);

    @Override
    public void messageReceived(
            final ChannelHandlerContext ctx, MessageEvent e) throws InterruptedException {
        if(!(e.getMessage() instanceof ChannelBuffer))return;

        ChannelBuffer pack= ((ChannelBuffer)e.getMessage());

        if(pack!=null)
            this.objectSession.getHandBuffers().add(pack);
            this.processSession.setBuffer(pack);
        ((ExecutionHandler) ctx.getPipeline().get("executor")).getExecutor().execute(this.processSession);

    }

    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

        Channel channel=e.getChannel();

        countConnection.incrementAndGet();
        this.objectSession=new ObjectSession(channel);

        this.processSession=new ProcessSession(this.objectSession);
        /**
         * 注册player的session
         */
        player=new PlayerInstance(this.objectSession);

        PlayerManagerService.SESSION_PLAYER_INSTANCE_MAP.put(this.objectSession,player);
        ctx.sendUpstream(e);
        if(MServerConfig.NETTY_DEBUG)LOG.info("Concurrent  connection... " +countConnection.get());
    }


    @Override
    public void channelClosed(
            ChannelHandlerContext ctx, ChannelStateEvent e){
        try{
            DestroySession(ctx);
            ctx.sendUpstream(e);
        }catch (Exception ee){
            LOG.warn("close channel error!",ee);
        }
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        ctx.getChannel().close();
        ctx.sendUpstream(e);
    }

    private void  DestroySession(ChannelHandlerContext ctx){
        /**保存角色数据*/
        PlayerManagerService.SESSION_PLAYER_INSTANCE_MAP.get(this.objectSession).save();
        PlayerManagerService.SESSION_PLAYER_INSTANCE_MAP.remove(this.objectSession) ;
        this.objectSession.Destroy();
        this.objectSession=null;
        this.processSession=null;
        MServerFrameUtil.clearPipeline(ctx.getPipeline());
        if (MServerConfig.NETTY_DEBUG)LOG.info("channelClosed， Concurrent  connection... " +countConnection.decrementAndGet());
    }


    public ObjectSession getmSession() {
        return this.objectSession;
    }



}
